package com.yjw.demo.netty.nio;

import com.yjw.demo.netty.util.IoUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.UUID;

/**
 * @author: James Yin
 * @description: 客户端
 * @date: 3/18/2020 6:40 PM
 */
public class Client {

    private static final String DEFAULT_SERVER_IP = "127.0.0.1";
    private static final int DEFAULT_SERVER_PORT = 8888;

    public static void main(String[] args) {
        SocketChannel socketChannel = null;
        Selector selector = null;
        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open();
            // 设置非阻塞模式
            socketChannel.configureBlocking(false);
            // 建立连接
            boolean isConnect = socketChannel.connect(new InetSocketAddress(DEFAULT_SERVER_IP, DEFAULT_SERVER_PORT));
            if (isConnect) {
                // 注册读事件
                socketChannel.register(selector, SelectionKey.OP_READ);
                // 发送请求消息
                doWrite(socketChannel);
            } else {
                // 注册连接事件
                socketChannel.register(selector, SelectionKey.OP_CONNECT);
            }

        } catch (IOException e) {
            IoUtils.close(socketChannel, selector);
        }
    }

    /**
     * 发送请求信息
     *
     * @param socketChannel
     */
    private static void doWrite(SocketChannel socketChannel) throws IOException {
        String uuid = UUID.randomUUID().toString();
        byte[] byteArr = uuid.getBytes();
        ByteBuffer byteBuffer = ByteBuffer.allocate(byteArr.length);
        byteBuffer.put(byteArr);
        byteBuffer.flip();
        socketChannel.write(byteBuffer);
    }
}